package cn.fhj.util;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import freemarker.cache.FileTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * 封装FreeMarker的使用
 * 
 * @since Fan Houjun 2008-11-10
 */
public class FtlUtil {

	private static String build(Object data, String ftlPath, Configuration config) {
		try {
			config.setEncoding(Locale.getDefault(), "UTF-8");
			Template template = config.getTemplate(ftlPath);
			template.setEncoding("UTF-8");
			StringWriter writer = new StringWriter();
			final Map map = toMap(data);
			template.process(map, writer);
			return writer.toString();
		} catch (Exception e) {
			throw new MsgException("解析ftl模板出错：" + ftlPath, e);
		}
	}

	private static Map toMap(Object data) {
		if (data instanceof Map) {
			return (Map) data;
		}
		Map map = new HashMap();
		map.put("data", data);
		return map;
	}

	/**
	 * 通过物理路径加载模板
	 * 
	 * @param data
	 *            模板键值对
	 * @param ftlFilename
	 *            模板存放完整路径
	 */
	public static String build(Object data, String ftlFilename) {
		Configuration config = new Configuration();
		config.setEncoding(Locale.getDefault(), "UTF-8");
		try {
			config.setTemplateLoader(new FileTemplateLoader(new File(ftlFilename).getParentFile()));
		} catch (IOException e) {
			throw new MsgException("解析ftl模板出错：" + ftlFilename, e);
		}
		return build(data, new File(ftlFilename).getName(), config);
	}

}
